package org.sction;

import java.io.BufferedReader;
import java.io.Console;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.logicalcobwebs.proxool.ProxoolDataSource;
import org.sction.manager.database.SpringDBHelper;
import org.springframework.jdbc.core.JdbcTemplate;


/**
 * @author 作者 : Administrator
 * @version 创建时间：2013年8月19日 下午5:16:43
 * 
 *          类说明
 */
public class DBTools {
	private static String dir = null;

	// SpringDBHelper
	public static void main(String[] args) {
		String path = ConfigTools.getPropertiesPath(args);
		if (path != null) {
			Properties config = ConfigTools.getProperties(path);// 记录配置项
			File filep = new File(path);
			if (filep.exists()) {
				dir = filep.getParent();
				System.out.println(dir);
			}
			if (config != null) {

				String driver = ConfigTools.getPropertie(config, "jdbc.driver");
				String url = ConfigTools.getPropertie(config, "jdbc.url");
				String user = ConfigTools.getPropertie(config, "jdbc.user");
				String password = ConfigTools.getPropertie(config,
						"jdbc.password");
				ProxoolDataSource pds = new ProxoolDataSource();
				pds.setDriver(driver);
				pds.setDriverUrl(url);
				pds.setUser(user);
				pds.setPassword(password);
				pds.setTrace(true);
				pds.setMaximumConnectionCount(500);
				pds.setMinimumConnectionCount(5);
				pds.setAlias("aideDbTools");
				JdbcTemplate jdbc = new JdbcTemplate(pds);
				SpringDBHelper.setJdbc(jdbc);
				SpringDBHelper.setShowSql(true);
				System.out.println("连接到数据：" + url);
				Console cons = System.console();
				while (true) {
					switch (selshow(cons)) {
					case 0:
						System.out.println("byebye!");
						System.exit(0);
						break;
					case 1:
						inputsql(cons);
						break;
					case 2:
						inputpath(cons);
						break;
					default:
						break;
					}
				}
			}
		}
		System.exit(0);
	}

	public static void inputsql(Console cons) {
		System.out.println("请输入SQL语句：");
		String sql = cons.readLine();
		if (sql.trim().startsWith("select ")) {

			List<Map<String, Object>> list = SpringDBHelper.queryForList(sql,
					new Object[] {});
			if (list == null) {
				System.out.println("查询结果如下(空)：");
				System.out
						.println("=============================================");
			} else {
				System.out.println("查询结果如下(" + list.size() + ")：");
				System.out
						.println("=============================================");
				int i = 0;
				for (Map<String, Object> map : list) {
					System.out.println(map);
					System.out.println(i++
							+ "=============================================");
				}
			}
		} else if (sql.trim().startsWith("delete ")) {
			System.out.println("删除："
					+ SpringDBHelper.delete(sql, new Object[] {}) + "条记录");
		} else if (sql.trim().startsWith("update ")) {
			System.out.println("更新："
					+ SpringDBHelper.update(sql, new Object[] {}) + "条记录");
		} else if (sql.trim().startsWith("insert ")) {
			System.out.println("添加："
					+ SpringDBHelper.insert(sql, new Object[] {}) + "条记录");
		} else {
			System.out.println("执行SQL：" + sql);
			try {
				SpringDBHelper.execute(sql);
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println("执行完成。");
		}
		System.out.println("=====================END=====================");

	}

	public static void inputpath(Console cons) {
		System.out.println("请输入SQL文件路径：");
		String path = cons.readLine();
		if (path.equals("")) {
			path = (dir != null ? dir : "");
			path = path + "/init.sql";
		}
		File sqlfile = new File(path);
		if (sqlfile.exists()) {
			try {
				StringBuffer sb = new StringBuffer("");
				FileReader reader = new FileReader(sqlfile);
				BufferedReader br = new BufferedReader(reader);
				String str = null;
				boolean more_zs = false;
				List<String> sqls = new ArrayList<String>();
				while ((str = br.readLine()) != null) {
					if (str.trim().toLowerCase().equals("go")) {
						sqls.add(sb.toString());
						sb = new StringBuffer("");
					} else {
						if (str.startsWith("/*")) {
							more_zs = true;
						}
						if (str.startsWith("*/")) {
							more_zs = false;
							continue;
						}
						// 多上注视跳过
						if (more_zs) {
							continue;
						}
						// 单行注视跳过
						if (!more_zs && str.startsWith("--")) {
							continue;
						}
						sb.append(str);
					}
				}
				br.close();
				reader.close();
				String[] a = new String[sqls.size()];
				sqls.toArray(a);
				SpringDBHelper.getJdbc().batchUpdate(a);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static int selshow(Console cons) {
		System.out.println("请选择：");
		System.out.println("1.执行sql语句");
		System.out.println("2.执行sql文件");
		System.out.println("0.退出程序");
		String sel = cons.readLine();
		try {
			int i = Integer.parseInt(sel);
			return i;
		} catch (Exception e) {
			return selshow(cons);
		}
	}
}
